package com.ruoyi.project.wceimms.controller;

import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.fastjson2.JSON;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.ruoyi.project.wceimms.domain.WceimmsIrfDetail;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFPicture;
import org.apache.poi.xssf.usermodel.XSSFShape;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.wceimms.domain.WceimmsIrfMain;
import com.ruoyi.project.wceimms.service.IWceimmsIrfMainService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 装置送检接收单主单（Inspection Receipt Form）Controller
 * 
 * @author hanl
 * @date 2025-02-06
 */
@RestController
@RequestMapping("/wceimms/inspectionReceiptForm")
public class WceimmsIrfMainController extends BaseController
{
    @Autowired
    private IWceimmsIrfMainService wceimmsIrfMainService;

    /**
     * 查询装置送检接收单主单（Inspection Receipt Form）列表
     */
    @PreAuthorize("@ss.hasPermi('wceimms:inspectionReceiptForm:list')")
    @GetMapping("/list")
    public TableDataInfo list(WceimmsIrfMain wceimmsIrfMain)
    {
        startPage();
        List<WceimmsIrfMain> list = wceimmsIrfMainService.selectWceimmsIrfMainList(wceimmsIrfMain);
        return getDataTable(list);
    }

    /**
     * 导出装置送检接收单主单（Inspection Receipt Form）列表
     */
    @PreAuthorize("@ss.hasPermi('wceimms:inspectionReceiptForm:export')")
    @Log(title = "装置送检接收单主单（Inspection Receipt Form）", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WceimmsIrfMain wceimmsIrfMain)
    {
        List<WceimmsIrfMain> list = wceimmsIrfMainService.selectWceimmsIrfMainList(wceimmsIrfMain);
        ExcelUtil<WceimmsIrfMain> util = new ExcelUtil<WceimmsIrfMain>(WceimmsIrfMain.class);
        util.exportExcel(response, list, "装置送检接收单主单（Inspection Receipt Form）数据");
    }

    /**
     * 获取装置送检接收单主单（Inspection Receipt Form）详细信息
     */
    @PreAuthorize("@ss.hasPermi('wceimms:inspectionReceiptForm:query')")
    @GetMapping(value = "/{irfMainId}")
    public AjaxResult getInfo(@PathVariable("irfMainId") Long irfMainId)
    {
        return success(wceimmsIrfMainService.selectWceimmsIrfMainByIrfMainId(irfMainId));
    }

    @GetMapping(value="/getPdf/{irfMainId}")
    public void getPdf(@PathVariable("irfMainId") Long irfMainId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        File tmpFile = FileUtils.createTmpFile("test.xls");
        //文件模板输入流，将excel模板放到resources目录下
        InputStream inputStream = new ClassPathResource("excel/送检接收单.xls").getInputStream();
        WceimmsIrfMain wceimmsIrfMain = wceimmsIrfMainService.selectWceimmsIrfMainByIrfMainId(irfMainId);
        List<WceimmsIrfDetail> detailList = wceimmsIrfMain.getDetailList();
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (WceimmsIrfDetail detail : detailList) {
            detail.setMaintenanceNumber("");
            // 使用 FastJSON 将对象转换为 Map
            Map<String, Object> map = (Map<String, Object>) JSON.toJSON(detail);
            String items=detail.getItems();
            map.put("尺寸",items.contains("尺寸")?"√":"");
            map.put("测厚",items.contains("测厚")?"√":"");
            map.put("磁粉",items.contains("磁粉")?"√":"");
            map.put("维修",items.contains("维修")?"√":"");
            map.put("试压",items.contains("试压")?"√":"");

            String mark=detail.getMark();
            map.put("打码",mark.contains("打码")?"√":"");
            map.put("扎带",mark.contains("扎带")?"√":"");

            map.put("checkBox","\u2610");
            mapList.add(map);
        }
        try (ExcelWriter excelWriter = EasyExcel.write(tmpFile).withTemplate(inputStream).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(wceimmsIrfMain, writeSheet);
            excelWriter.fill(mapList,fillConfig, writeSheet);
        }

        inputStream = new FileInputStream(tmpFile);
        //使用poi替换excel2003图片
        HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
        // 获取第一个工作表
        HSSFSheet sheet = workbook.getSheetAt(0);
        HSSFShape shape= sheet.getDrawingPatriarch().getChildren().get(0);
        HSSFClientAnchor anchor = (HSSFClientAnchor)shape.getAnchor();
        anchor.setRow1(anchor.getRow1()+detailList.size()-1);
        anchor.setRow2(anchor.getRow2()+detailList.size()-1);
        InputStream picInputStream=new ClassPathResource("excel/hanlei.png").getInputStream();
        byte[] picByte= IOUtils.toByteArray(picInputStream);
        int picIndex = workbook.addPicture(picByte, workbook.PICTURE_TYPE_PNG);
        sheet.getDrawingPatriarch().createPicture(anchor,picIndex);
        sheet.getDrawingPatriarch().removeShape(shape);
        workbook.write(tmpFile);

        String realFileName = "送检接收单（"+wceimmsIrfMain.getIrfNumber()+").pdf";
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        com.ruoyi.common.utils.file.FileUtils.setAttachmentResponseHeader(response, realFileName);
//        com.ruoyi.common.utils.file.FileUtils.writeBytes(tmpFile.getAbsolutePath(),outputStream);

        //excel转pdf
        long startTime = System.currentTimeMillis(); // 记录开始时间

        inputStream = new FileInputStream(tmpFile);
        IConverter converter = LocalConverter.builder().workerPool(20, 25, 2, TimeUnit.SECONDS).build();
        converter.convert(inputStream).as(DocumentType.XLS).to(outputStream).as(DocumentType.PDF).execute();
        FileUtils.delete(tmpFile);
        inputStream.close();
        long endTime = System.currentTimeMillis(); // 记录结束时间
        long elapsedTime = endTime - startTime; // 计算耗时
        System.out.println("Excel转PDF耗时: " + elapsedTime + "毫秒"); // 输出耗时

    }

    /**
     * 新增装置送检接收单主单（Inspection Receipt Form）
     */
    @PreAuthorize("@ss.hasPermi('wceimms:inspectionReceiptForm:add')")
    @Log(title = "装置送检接收单主单（Inspection Receipt Form）", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WceimmsIrfMain wceimmsIrfMain)
    {
        wceimmsIrfMain.setCreateBy(getUsername());
        return toAjax(wceimmsIrfMainService.insertWceimmsIrfMain(wceimmsIrfMain));
    }

    /**
     * 修改装置送检接收单主单（Inspection Receipt Form）
     */
    @PreAuthorize("@ss.hasPermi('wceimms:inspectionReceiptForm:edit')")
    @Log(title = "装置送检接收单主单（Inspection Receipt Form）", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WceimmsIrfMain wceimmsIrfMain)
    {
        wceimmsIrfMain.setUpdateBy(getUsername());
        return toAjax(wceimmsIrfMainService.updateWceimmsIrfMain(wceimmsIrfMain));
    }

    /**
     * 删除装置送检接收单主单（Inspection Receipt Form）
     */
    @PreAuthorize("@ss.hasPermi('wceimms:inspectionReceiptForm:remove')")
    @Log(title = "装置送检接收单主单（Inspection Receipt Form）", businessType = BusinessType.DELETE)
	@DeleteMapping("/{irfMainIds}")
    public AjaxResult remove(@PathVariable Long[] irfMainIds)
    {
        return toAjax(wceimmsIrfMainService.deleteWceimmsIrfMainByIrfMainIds(irfMainIds));
    }
}
